<?php
namespace Home\Logic;

use My\Model\DistributionShopOrderModel;

class DistributionShopPayLogic {
	
	/**
	 * 退款回调
	 * @param string $refundNo(*) 退款编号
	 * @param array $wparam(*) 退款参数
	 * array(
	 * 	'refundStatus' => 'SUCCESS',
	 * )
	 */
	public static function refundCallBack($refundNo, $wparam) {
		$status = $wparam["refundStatus"];
		$refund = M("DistributionShopRefund")->where("refundNo='%s'", $refundNo)->find();
		if ( $refund ) {
			// 更新退款申请状态
			M("DistributionShopRefund")->where("refundNo='%s'", $refund['refundNo'])->save(array(
				'status' => $status ? DistributionShopOrderModel::REFUND_STATUS_BACK : DistributionShopOrderModel::REFUND_STATUS_FAIL,
			));
			if ( $refund['all'] ) { // 全额退款
				// 更新订单退款状态
				M("DistributionShopOrder")->where(array(
					'order_id' => $refund['orderNo'],
					'order_status' => DistributionShopOrderModel::ORDER_STATUS_REFUND_PROCESSING,
				))->save(array(
					'order_status' => $status ? DistributionShopOrderModel::ORDER_STATUS_REFUND_SUCCESS : DistributionShopOrderModel::ORDER_STATUS_REFUND_FAIL,
					'refund_status' => DistributionShopOrderModel::ORDER_REFUND_STATUS_FINISH,
				));
			} else { // 部分退款
				// 查询订单退款数量
				$count = M("DistributionShopRefund")->where(array(
					'orderNo' => $refund['orderNo'],
					'status' => array('not in', array(
									DistributionShopOrderModel::REFUND_STATUS_UNREAD,
									DistributionShopOrderModel::REFUND_STATUS_AGREE,
								)),
				))->count();
				// 全部处理完成时
				if ( !$count ) {
					// 更新订单退款状态
					M("DistributionShopOrder")->where(array(
						'order_id' => $refund['orderNo'],
					))->save(array(
						'refund_status' => DistributionShopOrderModel::ORDER_REFUND_STATUS_FINISH,
					));
				}
			}
		}
	}

	/**
	 *  获得接口配置
	 * @param unknown $cfg
	 * array(
	 * 	'paymentMethod', // 支付方式(*): Alipay,WxTenpay
	 * )
	 * @return multitype:
	 */
	public static function getApiConfig( $cid, $cfg ) {
		// 支付方式
		$apitype = $cfg['paymentMethod'];
		// 获得支付接口
		$productPayApi = D("ProductPayApi")->where("cid=%d and tag='%s'", $cid, $apitype)->find(); // 获得支付方式配置
		$config = (array)unserialize($productPayApi['cfg']);
		// 附加参数
		$config['wparam'] or $config['wparam'] = array();
		// 不同支付方式下的配置
		if ( 'WxTenpay' == $apitype) { // 微信支付时读取开发者配置
			$wechat = M('Wechat')->where(array('cid'=>$cid))->find();
			$config = array_merge($config, array('appid' => $wechat['appid'], 'appsecret' => $wechat['appsecret'], ));
		}
		return $config;
	}
	
	
	/**
	 * 支付回调接口
	 * @param unknown $apitype
	 * @return Ambigous <string, mixed>
	 */
	public static function getCallBackUrl( $apitype, $cid, $controllerName, $action, $debug = false ) {
		$controllerName or $controllerName = CONTROLLER_NAME;
		$action or $action = "notify";
		return U("Home/{$controllerName}".($debug?'Debug':'')."/{$action}", array('sid' => $cid, 'apitype' => $apitype), false, true);
	}
	
}